import React from 'react';
export type Locale = 'en' | 'es' | 'fr' | 'ja' | 'ru';

const SUPPORTED_LOCALES: Locale[] = ['en', 'es', 'fr', 'ja', 'ru'];
const DEFAULT_LOCALE: Locale = 'ja';

function getInitialLocale(): Locale {
  if (typeof navigator === 'undefined') return DEFAULT_LOCALE;
  const browserLang = ((navigator as any).language || (navigator as any).userLanguage || DEFAULT_LOCALE).slice(0, 2);
  // 验证浏览器语言是否在支持的语言列表中
  return SUPPORTED_LOCALES.includes(browserLang as Locale) ? (browserLang as Locale) : DEFAULT_LOCALE;
}

let currentLocale: Locale = getInitialLocale();

const localeCache: Record<string, any> = {};
let currentMessages: Record<string, any> = {};
let fallbackMessages: Record<string, any> = {};

// 使用 Vite 的 import.meta.glob 进行受控的动态导入，确保打包后路径正确
const localeModules: Record<string, () => Promise<any>> = import.meta.glob('./locales/*.json');

const listeners = new Set<() => void>();
let i18nTick = 0; // 用于强制触发订阅者更新（即使 locale 未变化）

function notifySubscribers() {
  i18nTick++;
  listeners.forEach((fn) => {
    try { fn(); } catch {}
  });
}

export function subscribeI18n(listener: () => void) {
  listeners.add(listener);
  return () => { listeners.delete(listener); };
}

export function setLocale(locale: Locale) {
  currentLocale = locale;
  try { localStorage.setItem('app_locale', locale); } catch (e) {}
  // 同步到文档，便于全局样式按语言设置字体
  try {
    if (typeof document !== 'undefined') {
      document.documentElement.setAttribute('data-locale', locale);
      document.documentElement.setAttribute('lang', locale);
    }
  } catch (e) {}
  // Load target locale messages, then notify to avoid flicker/incorrect language
  loadLocaleMessages(locale).then((msgs) => {
    currentMessages = msgs || {};
    notifySubscribers();
  });
}

export function getLocale() {
  try {
    const saved = localStorage.getItem('app_locale');
    // 验证 localStorage 中的语言是否在支持列表中
    if (saved && SUPPORTED_LOCALES.includes(saved as Locale)) {
      return saved as Locale;
    }
  } catch (e) {}
  return currentLocale;
}

export async function loadLocaleMessages(locale: Locale) {
  if (localeCache[locale]) return localeCache[locale];
  try {
    const key = `./locales/${locale}.json`;
    const loader = localeModules[key];
    if (loader) {
      const mod = await loader();
      const msgs = (mod && (mod.default ?? mod)) || {};
      localeCache[locale] = msgs;
      return localeCache[locale];
    }
  } catch (e) {}
  if (locale !== 'en') return loadLocaleMessages('en');
  return {};
}

// Async translate kept for compatibility
export async function t(key: string, localeParam?: Locale) {
  const locale = localeParam || (getLocale() as Locale);
  const msgs = await loadLocaleMessages(locale);
  const value = resolveKey(msgs, key);
  if (value != null) return value;
  const enMsgs = await loadLocaleMessages('en');
  const fallback = resolveKey(enMsgs, key);
  return fallback != null ? fallback : key;
}

function resolveKey(obj: any, path: string) {
  const parts = path.split('.');
  let cur: any = obj;
  for (const p of parts) {
    if (cur && Object.prototype.hasOwnProperty.call(cur, p)) cur = cur[p];
    else return null;
  }
  return cur;
}

// Sync translate: use loaded messages immediately, fallback to key if not loaded yet
export function tt(key: string): string {
  const val = resolveKey(currentMessages, key);
  if (val != null) return String(val);
  const fb = resolveKey(fallbackMessages, key);
  if (fb != null) return String(fb);
  return key;
}

// React hook for i18n
// Lightweight; avoids external context by using subscription
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function useI18n() {
  const snapshot = React.useSyncExternalStore(
    subscribeI18n,
    () => `${getLocale()}#${i18nTick}`,
    () => `${getLocale()}#${i18nTick}`
  );
  const locale = getLocale();
  const tBound = React.useCallback((key: string) => tt(key), [snapshot]);
  return { t: tBound, locale, setLocale } as const;
}

// 将内部 locale 转换为接口要求的 language 参数
export function toApiLanguageCode(locale: Locale): string {
  // 约定：xby=西班牙语(es)，fy=法语(fr)，jp=日语(ja)，en=英语(en)，ey=俄语(ru)
  switch (locale) {
    case 'es': return 'xby';
    case 'fr': return 'fy';
    case 'ja': return 'jp';
    case 'ru': return 'ey';
    case 'en':
    default: return 'en';
  }
}

// initial load: fallback and current locale
(async () => {
  try { 
    const saved = localStorage.getItem('app_locale'); 
    // 验证 localStorage 中的语言是否在支持列表中
    if (saved && SUPPORTED_LOCALES.includes(saved as Locale)) {
      currentLocale = saved as Locale;
    }
  } catch {}
  // 初始化阶段同步 DOM 属性，确保首屏/刷新后字体正确
  try {
    if (typeof document !== 'undefined') {
      document.documentElement.setAttribute('data-locale', getLocale() as string);
      document.documentElement.setAttribute('lang', getLocale() as string);
    }
  } catch {}
  try {
    fallbackMessages = await loadLocaleMessages('en');
  } catch {}
  try {
    currentMessages = await loadLocaleMessages(getLocale() as Locale);
  } catch {}
  notifySubscribers();
})();
